package com.wisdom.system.common.util;

import com.alibaba.fastjson.JSONObject;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//字符串工具类
public class StringUtil {
    public static boolean isEmpty(String str) {
        if (str != null && str.trim().length() > 0) {
            return false;
        }
        return true;
    }


    public static boolean isNotEmpty(String str) {
        if (str != null && str.trim().length() > 0) {
            return true;
        }
        return false;
    }
    /**
     * 字符串模板替换
     * 模板格式 ${key}；参数格式"{key:'值'}"
     *
     * @param content
     * @param param
     * @return
     */
    public static String template(String content, String param) {
        if (StringUtil.isEmpty(param)) {
            String regex = "\\#\\{\\w+\\}";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(content);
            content = matcher.replaceAll("");
            return content;
        }
        JSONObject jsonObject = JSONObject.parseObject(param);
        return template(content, jsonObject);
    }

    /**
     * 字符串模板替换
     * 模板格式 ${key}；参数格式 JsonObject: {key:'值'}
     *
     * @param content
     * @param jsonObject
     * @return
     */
    public static String template(String content, JSONObject jsonObject) {
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            String regex = "\\#\\{" + entry.getKey() + "\\}";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(content);
            String value = entry.getValue() == null ? "" : entry.getValue().toString();
            content = matcher.replaceAll(value);
        }
        String regex = "\\#\\{\\w+\\}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(content);
        content = matcher.replaceAll("");
        return content;
    }

}
